//
//  XPStatusesViewModel.swift
//  SinaWeibo
//
//  Created by 徐攀 on 16/5/13.
//  Copyright © 2016年 徐攀. All rights reserved.
//

import UIKit

class XPStatusesListViewModel: NSObject {
    
    var statusesCell: [XPStatusesCellViewModel]?
    
    func requestStatuses(accessToken: String, isPullUp: Bool ,complete:(isSuccess: Bool, tips: String)->()) {
        
        // 最新微博id
        var sinceId: Int64 = 0
        // 当前页最后一条微博id
        var maxId: Int64 = 0

        //  判断是上拉加载还是下拉刷新
        if isPullUp {
            if let lastWeiboId = statusesCell?.last?.statuses?.id {
                maxId = lastWeiboId - 1
            }
        }else {
            
            if let firstWeiboId = statusesCell?.first?.statuses?.id {
                sinceId = firstWeiboId
            }
        }
        
        XPNetworkTool.sharedTools.requestStatuses(accessToken, maxId:maxId, sinceId: sinceId ,resultClosure: { (response, error)->() in
            if error != nil {
                print("网络请求异常,原因：\(error)")
                complete(isSuccess: false, tips: "没有网络啦~")
                return
            }
            guard let dict = response as? [String: AnyObject] else {
                print("不是一个正确的字典格式")
                complete(isSuccess: false, tips: "请求出错啦~")
                return
            }
            guard let statusesArray = dict["statuses"] as? [[String: AnyObject]]  else {
                print("数据解析错误")
                complete(isSuccess: false, tips: "请求出错啦~")
                return
            }
            
            var tempArr = [XPStatusesCellViewModel]()
            for value in statusesArray {
                let status = XPStatuses(dict: value)
                let statusCellViewModel = XPStatusesCellViewModel(statuses: status)
                tempArr.append(statusCellViewModel)
            }

            // 根OC一样，如果不初始化，数组是赋不上值的
            if self.statusesCell?.count == nil {
                
                self.statusesCell = [XPStatusesCellViewModel]()
            }
            
            if isPullUp {
                self.statusesCell?.appendContentsOf(tempArr)
            }else {
                self.statusesCell?.insertContentsOf(tempArr, at: 0)
            }
            if tempArr.count > 0 {
                complete(isSuccess: true, tips: "\(tempArr.count)条新微博")
            }else {
                complete(isSuccess: true, tips: "暂无新微博")
            }
        })
    }
}
